package com.example.administrator.application

import android.support.v7.app.AppCompatActivity
import java.util.*

open class ActivityManager private constructor() {
    private var mActivityStack: ArrayList<AppCompatActivity>? = null

    init {
        mActivityStack = ArrayList()
    }

    companion object {
        /**
         * 栈中保存Activity的最大数量
         */
        private const val MAX_COUNT = 20
        private var sInstance: ActivityManager? = null

        fun get(): ActivityManager? {
            if (sInstance == null) {
                synchronized(ActivityManager::class.java) {
                    if (sInstance == null) {
                        sInstance = ActivityManager()
                    }
                }
            }
            return sInstance
        }
    }

    /**
     * 添加Activity到栈中
     */
    fun push(activity: AppCompatActivity?) {
        if(activity != null && !activity.isFinishing) {
            if(mActivityStack != null && mActivityStack!!.size > MAX_COUNT) {
                val ac = mActivityStack?.get(mActivityStack!!.size - 1)
                if(ac?.isFinishing == false) {
                    ac.finish()
                }
                mActivityStack?.remove(ac)
            }
            mActivityStack?.add(activity)
        }
    }

    /**
     * 从栈中移除Activity
     */
    fun pop(activity: AppCompatActivity?) {
        if(mActivityStack?.isEmpty() == false && mActivityStack?.contains(activity) == true) {
            mActivityStack?.remove(activity)
        }
    }

    /**
     * 获取栈顶Activity
     */
    fun getTopActivity(): AppCompatActivity? {
        if(mActivityStack?.isEmpty() == false) {
            return mActivityStack?.get(mActivityStack!!.size - 1)
        }
        return null
    }

    /**
     * 回退到指定activity
     */
    fun popToActivity(num: Int = 1) {
        if(mActivityStack?.isEmpty() == false && num > 0) {
            var count = num
            if(num > mActivityStack!!.size) {
                count = mActivityStack!!.size
            }
            for(i in 0 until count) {
                val activity = mActivityStack?.removeAt(mActivityStack!!.size - 1)
                if(activity?.isFinishing == false) {
                    activity.finish()
                }
            }
        }
    }
}